package cn.kgc.utils;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author YC
 */
@Slf4j
@Component
public class SmsSender {

    @Resource
    private SmsProperties smsProperties;

    private Client createClient() throws Exception {
        Config config = new Config()
                .setAccessKeyId(smsProperties.getKeyId())
                .setAccessKeySecret(smsProperties.getKeySecret());
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new Client(config);
    }

    /**
     * 第三方接口阿里云平台：发送短信
     */
    public void sendMsg(String phoneNumber, String code) throws
            Exception {
        Client client = createClient();
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(phoneNumber)
                .setSignName(smsProperties.getSignName())
                .setTemplateCode(smsProperties.getTemplateCode())
                .setTemplateParam("{\"code\":\"" + code + "\"}");
        RuntimeOptions runtime = new RuntimeOptions();
        client.sendSmsWithOptions(sendSmsRequest, runtime);
    }

}